package com.stu.controller;

import com.stu.commons.ServerResponse;
import com.stu.pojo.Likes;
import com.stu.utils.JwtUtil;
import org.redisson.api.RedissonClient;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/likes")
public class LikesController {

    @Autowired
    private RedissonClient redissonClient;  // 使用 RedissonClient 而非 Redisson

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("postlikes")
    @ResponseBody
    public ServerResponse postlikes(String token, Integer evaluationId) {
        String keys = "likes::" + evaluationId;
        System.out.println("keys:");
        System.out.println(keys);

        // 使用新的 JwtUtil 来解析 token 获取用户 ID
        String userIdStr = JwtUtil.getUserIdFromToken(token);  // 获取字符串类型的用户 ID
        Integer userId = Integer.valueOf(userIdStr);  // 将 String 类型的 userId 转换为 Integer 类型

        RLock redissonLock = redissonClient.getLock(keys + "key");  // 使用 redissonClient 获取锁
        redissonLock.lock();

        Long result = null;

        try {
            if (userId != null) {
                Likes likes = new Likes();
                likes.setLikeStatus(1);
                likes.setLikeTime("2022/09/20 17:50:30");
                likes.setUserId(userId);
                likes.setEvaluationId(evaluationId);

                // 将点赞信息保存到 Redis
                result = redisTemplate.opsForList().rightPush(keys, likes);
            } else {
                return ServerResponse.fail("未登录", null);
            }
        } finally {
            redissonLock.unlock();  // 释放锁
        }

        return ServerResponse.success("", result);
    }
}
